package com.chamberlain.equipment.mqtt;

import com.alibaba.fastjson2.JSONObject;
import com.chamberlain.common.core.domain.entity.Equipment;
import com.chamberlain.equipment.service.IEquipmentService;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * @author: CYY
 * @date: 2024/4/5
 */
@Component
public class PublishCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(MqttPublishClient.class);

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private IEquipmentService equipmentService;

    private static MqttClient client;

    private static String _topic;
    private static String _qos;
    private static String _msg;

    public void setClient(MqttClient client) {
        PublishCallback.client = client;
    }

    @Override
    public synchronized void connectionLost(Throwable throwable) {
        // 连接丢失后，一般在这里面进行重连
        logger.info("连接断开，重连");
        if (client == null || !client.isConnected()) {
            mqttConfig.getMqttPushClient();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        // subscribe后得到的消息会执行到这里面
        logger.info("接收消息主题 : " + topic);
        logger.info("接收消息Qos : " + mqttMessage.getQos());
        logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));

        _topic = topic;
        _qos = mqttMessage.getQos() + "";
        _msg = new String(mqttMessage.getPayload());

        JsonParser jsonParser=new JsonParser();
        JsonObject jsonObject=jsonParser.parse(_msg).getAsJsonObject();

        Equipment equipment=new Equipment();
        equipment.setMac(jsonObject.get("mac").getAsString());
        equipment.setValue(Long.parseLong(jsonObject.get("value").getAsString()));
        equipmentService.updateEquipmentByMac(equipment);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------" + iMqttDeliveryToken.isComplete());
    }

    //别的Controller层会调用这个方法来  获取接收到的硬件数据
    public String receive() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("topic", _topic);
        jsonObject.put("qos", _qos);
        jsonObject.put("msg", _msg);
        return jsonObject.toString();
    }
}